<template>
  <div class="setting-container">
    <el-form ref="form" :model="formData" :rules="rules">
      <el-form-item label="密码" prop="password">
        <el-input v-model.trim="formData.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model.trim="formData.confirmPassword"
          placeholder="请输入确认密码"
        />
      </el-form-item>
      <el-button
        :loading="loading"
        class="login-btn"
        type="primary"
        @click="handleSubmit"
      >
        提交
      </el-button>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { updateUser } from '@/apis/user'
  import { validatePassword } from '@/utils/validator'

  export default {
    data() {
      return {
        title: this.$baseTitle,
        formData: {
          password: '',
          confirmPassword: '',
        },
        rules: {
          password: [
            {
              required: true,
              trigger: 'change',
              validator: validatePassword,
            },
          ],
          confirmPassword: [
            {
              required: true,
              trigger: 'change',
              validator: validatePassword,
            },
          ],
        },
        loading: false,
      }
    },
    computed: {
      ...mapGetters({
        organInfo: 'user/organInfo',
      }),
    },
    methods: {
      handleSubmit() {
        this.$refs.form.validate(async (valid) => {
          if (valid) {
            try {
              const { password, confirmPassword } = this.formData
              if (password !== confirmPassword) {
                this.$baseMessage('请确保密码和确认密码一致', 'error')
                return
              }

              this.loading = true
              await updateUser(this.formData)
              this.$baseMessage('操作成功', 'success')
            } finally {
              this.loading = false
            }
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .setting-container {
    width: 500px;
  }
</style>
